package com.glodon.paas.account.security.cas.filter;

import static com.google.common.base.Objects.*;
import static com.google.common.base.Strings.*;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.context.support.SpringBeanAutowiringSupport;

import com.glodon.paas.account.api.bean.User;
import com.glodon.paas.account.security.common.PostAuthHandler;
import com.glodon.paas.account.security.spring.LoginUser;
import com.glodon.paas.account.web.util.CookieUtils;

/**
 * Serve TGT based SSO
 *
 * @author Don Li
 */
public class CasSsoFilter implements Filter {

    private static final Logger LOGGER = LoggerFactory.getLogger(CasSsoFilter.class);

    @Value("${tgc.name}")
    private String tgcName;

    @Autowired
    private PostAuthHandler postAuthHandler;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        SpringBeanAutowiringSupport.processInjectionBasedOnServletContext(this, filterConfig.getServletContext());
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest httpReq = (HttpServletRequest) request;
        HttpServletResponse httpResp = (HttpServletResponse) response;

        final String serviceId = firstNonNull(httpReq.getParameter("service"), "account");
        final String tgtId = CookieUtils.getValue(tgcName, httpReq);

        if (!isNullOrEmpty(tgtId)) {
            // having tgt, then check tgt
            LoginUser user = postAuthHandler.getUserByTgtId(tgtId);
            if (user != null) {
                // process valid tgt
                postAuthHandler.process(httpReq, httpResp, user, serviceId, tgtId, chain);
            } else {
                // tgt expired or invalid, then goto login page
                chain.doFilter(request, response);
            }
        } else {
            // no tgt, then proceed to login page
            chain.doFilter(request, response);
        }
    }

    @Override
    public void destroy() {
    }
}
